package org.iplatform.felicajack.mfcaccess;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;

import com.felicanetworks.mfc.Felica;

/**
 * Felica�Ƃ̐ڑ�(ServiceConnection)���Ǘ�����N���X
 *
 */
public class FelicaServiceConnection implements ServiceConnection {

    private static final FelicaServiceConnection instance = new FelicaServiceConnection();

    private Context context = null;

    /**
     * �ڑ����
     */
    private boolean connected = false;

    private FelicaServiceConnection() {

    };

    public static FelicaServiceConnection getInstance() {

        return instance;
    }

    public void setContext(final Context context) {

        this.context = context;
    }

    public void connect() throws Exception {

        if (context == null) {
            throw new Exception("connect error:Context is not set.");
        }

        if (connected) {
            // �ڑ��ς�
            return;
        }

        final Intent intent = new Intent();
        intent.setClass(context, Felica.class);
        if (!context.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
            throw new Exception("connect error:Context#bindService() failed.");
        }
        // �ڑ���ԕύX��onServiceConnected()���Ăяo���ꂽ�^�C�~���O�Ŏ��{
    }

    public void disconnect() throws Exception {

        if (context == null) {
            throw new Exception("connect error:Context is not set.");
        }

        if (!connected) {
            return;
        }

        context.unbindService(this);

        // �ڑ���Ԃ�����
        connected = false;
    }

    @Override
    public void onServiceConnected(final ComponentName name, final IBinder service) {

        // Felica�Ƃ̐ڑ����m�����ꂽ�̂ŁAFelica�C���X�^���X���擾����
        final Felica felica = ((Felica.LocalBinder)service).getInstance();
        MFCSampleUse.getInstance().setFelica(felica);
        connected = true;
    }

    @Override
    public void onServiceDisconnected(final ComponentName name) {

        // Felica�̐ݒ����
        MFCSampleUse.getInstance().setFelica(null);
        connected = false;
    }

}
